package cn.layfolk.seckill.web.controller;

import cn.layfolk.daimao.util.Webs;
import cn.layfolk.daimao.vo.TUser;
import cn.layfolk.seckill.redis.SeckillRedisKey;
import cn.layfolk.seckill.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class VerifyCodeController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @RequestMapping("/verifyCode")
    @ResponseBody
    public void verifyCode() throws IOException {

        //获取用户
        TUser user = null;
        if(user==null){
            System.out.println("获取用户失败");
            return;
        }
        //生成验证码
        String verifyCodeExp = VerifyCodeImgUtil.generateVerifyCode();
        Integer result = VerifyCodeImgUtil.calc(verifyCodeExp);
        // 得到验证码对应的结果，将结果以用户作为key，保存到Redis
        stringRedisTemplate.opsForValue().set(SeckillRedisKey.SECKILL_VERIFY_CODE_RET.getRealKey(user.getId()+""),
                result+"",SeckillRedisKey.SECKILL_VERIFY_CODE_RET.getExpireTime(),
                SeckillRedisKey.SECKILL_VERIFY_CODE_RET.getUnit());
        // 将生成好的验证码转换为图片，并响应到前端
        BufferedImage bufferedImage = VerifyCodeImgUtil.createVerifyCodeImg(verifyCodeExp);
        // 将内存中的图片写到响应流中
        ImageIO.write(bufferedImage,"JPEG", Webs.getResponse().getOutputStream());
    }
}